package com.gamota.mobi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.androidquery.AQuery;

import com.devspark.appmsg.AppMsg;
import com.gamota.mobi.background.BackgroundTasks;
import com.gamota.mobi.event.Event;
import com.google.analytics.tracking.android.EasyTracker;

import de.greenrobot.event.EventBus;

public class GiftCodeActivity extends Activity {
	
	private String userName;
	private AQuery aquery;
	private EventBus eventBus;
	private BackgroundTasks bgTask;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_giftcode);
		EasyTracker.getInstance().setContext(this);
		initVariables();
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		EasyTracker.getInstance().activityStop(this);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		EasyTracker.getInstance().activityStart(this);
	}

	protected void initVariables() {
		// TODO Auto-generated method stub
		userName = getIntent().getStringExtra(com.gamota.mobi.util.Constants.USER_NAME);
		aquery = new AQuery(this);
		eventBus = EventBus.getDefault();
		eventBus.register(this);
		bgTask = new BackgroundTasks(this);
		if(getIntent().hasExtra("giftCode"))
		{
			aquery.id(R.id.edit_giftcode).text(getIntent().getStringExtra("giftCode"));
		}
		aquery.id(R.id.btn_ok_giftcode).clicked(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(!TextUtils.isEmpty(aquery.id(R.id.edit_giftcode).getText().toString())){
					bgTask.giftcode(userName, aquery.id(R.id.edit_giftcode).getText().toString());
				} else {
					AppMsg.makeText(GiftCodeActivity.this, R.string.input_giftcode, AppMsg.STYLE_ALERT, null).show();
				}
			}
		});
	}
	
	public void onEventMainThread(Event.GiftCodeEvent event){
		if(event.isSuccess()){
			Toast.makeText(this, event.getMessage(), Toast.LENGTH_SHORT).show();
			Intent nofityIntent = new Intent("CLOSE_DIALOG");
			this.sendBroadcast(nofityIntent);
			finish();
		} else {
			AppMsg.makeText(this, event.getMessage(), AppMsg.STYLE_ALERT, null).show();
		}
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		eventBus.unregister(this);
	}
}
